﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace Meligo.DynamicViewCreator.DynamicViewItemEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class DynamicViewItemEventReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// An item is being updated.
        /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            SPListItem li = properties.ListItem;
            try
            {
                using (SPSite site = new SPSite(properties.SiteId))
                {
                    using (SPWeb web = site.OpenWeb(site.RootWeb.ID))
                    {
                        SPList findList = null;
                        try
                        {
                            string viewCaml = string.Empty; 
                            string viewName = string.Empty; 

                            if (li["ListName"] != null)
                            {
                                findList = web.Lists.TryGetList(li["ListName"].ToString());
                            }

                            if (li["ViewName"] != null )
                            {
                                viewName = li["ViewName"].ToString();
                            }

                            if (li["CamlQuery"] != null )
                            {
                                viewCaml = li["CamlQuery"].ToString();
                            }

                            if (findList != null)
                            {
                                SPView defaultView = findList.DefaultView;
                                SPViewCollection viewCollection = findList.Views;
                                System.Collections.Specialized.StringCollection viewFields = findList.Views[defaultView.ID].ViewFields.ToStringCollection();
                                viewCollection.Add(viewName, viewFields, viewCaml, 100, true, false);
                            }
                        }
                        catch (Exception ex)
                        {
                            Helpers.Logger.WriteToLog("An error has occured:", ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Helpers.Logger.WriteToLog("An error has occured:", ex);
            }

            base.ItemUpdating(properties);
        }
    }
}
